import QtQuick 1.1
import com.nokia.meego 1.1
import HttpUp 1.0

import "WebRequest.js" as Web

PostPage {
    signal loadStart
    signal loadStop
    property string imageurl
    property bool loading
    onLoadStart: { appWindow.loadStart(); loading = true }
    onLoadStop: { appWindow.loadStop(); loading = false }


    headerText: "发糗事"
    placeHolderText: "您可以在这里发表您自己的或者您听说过\n的糗事，与大家一起分享。\n"+
                     "您提交的糗事会在其他糗友审核之后发表，\n审核标准为：真实有笑点。与政治、色情无关。\n"+
                     "不包含邮件、电话、地址等联系信息，\n人脸可打码。"
    onPost: {
        if (postText.length<10){
            Web.showMessage("再多写点内容吧")
        } else
            diag.open()
    }
    Component.onDestruction: if (loading)
                                 loadStop()


    function postArticleHttp(){
      Web.showMessage("正在发送中...")   ;
     var url =     "http://m2.qiushibaike.com/article/create";
        var param = { content: postText.replace(/\n/g, "\\n"), anonymous: diag.selectedIndexes===1,
         allow_comment: diag.selectedIndexes===2}
        Web.sendWebRequest("POST", url,
                           loadCommentResult, JSON.stringify(param))

    }

    function loadCommentResult(oritxt){
        var obj = JSON.parse(oritxt)
        //var obj = JSON.parse(responseText)
        if (obj.err===0){
            showMessage("发表成功，人品加1。请耐心等待审核")
            pageStack.pop()
        } else {
            Web.showMessage(obj.err_msg)
        }
    }



    function postArticle(){
        Web.showMessage("正在发送中...")
        uploader.open("http://m2.qiushibaike.com/article/create")
        //uploader.
        uploader.addField("json",JSON.stringify({content: postText.replace(/\n/g,"\\n"),
                                                    anonymous: diag.selectedIndexes===1,
                                                    allow_comment: diag.selectedIndexes===2}))
        //uploader.setQiubaiToken()
        uploader.send(appWindow.qbtoken);
    }
    HttpUploader {
        id: uploader
        onUploadStateChanged: {
            if (uploadState===1) loadStart()
            if (uploadState===4) loadStop()
        }
        onStatusChanged: {
            if (status!=200){
                showMessage("error! status:"+status+"  "+errorString)
            } else {
                var obj = JSON.parse(responseText)
                if (obj.err===0){
                    Web.showMessage("发表成功，人品加1。请耐心等待审核")
                    pageStack.pop()
                } else {
                    Web.showMessage(obj.err_msg)
                }
            }
        }
    }

    MultiSelectionDialog {
        id: diag
        titleText: "确认操作"

        model: ListModel {
            ListElement { name: "匿名发送" }
            ListElement{name:"允许评论"}
        }
        acceptButtonText: "发送"
        rejectButtonText: "取消"
        onAccepted: postArticle()
    }



}
